//===============================================================================
// Microsoft patterns & practices
// SharePoint Guidance
//===============================================================================
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using SPGSharePointDataAccessQuickStart.Repository;
using SPGSharePointDataAccessQuickStart.Repository.SharePoint;
using SPGSharePointDataAccessQuickStart.Common.Constants;
using SPGSharePointDataAccessQuickStart.Repository.BusinessEntities;

namespace SPGSharePointDataAccessQuickStart.SharePoint
{
    public partial class SPGSharePointDataAccessQuickStart : System.Web.UI.Page
    {
        private int id;
        private Pattern pattern;

        #region Event Handlers

        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        protected void Page_Load(object sender, EventArgs e)
        {
            ListFormPageTitle.Text = "SPG SharePoint List Data Access QuickStart";
            LinkTitle.Text = "SPG";
            ItemProperty.Text = "SharePoint List Data Access QuickStart";
            LabelPageDescription.Text = "SPG SharePoint List Data Access QuickStart";

            SPWeb web = SPContext.Current.Site.RootWeb;
            
            ResetView(web);

            if ( PatternsList.SelectedIndex != -1 )
            {
                pattern = ParsePattern(PatternsList.SelectedValue);
            }
        }

        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        protected void AddButton_Click(object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Site.RootWeb;

            PerformAdd(web);
            PopulateIDsList(web);
            IDsList.SelectedValue = id.ToString();
            ResetView(web);  
        }

        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        protected void UpdateButton_Click(object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Site.RootWeb;

            PerformUpdate(web);
            ResetView(web);
        }

        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Site.RootWeb;

            PerformDelete(web);
            PopulateIDsList(web);
            ResetView(web);
        }

        #endregion

        #region Operations

        private void PerformAdd(SPWeb web)
        {
            switch ( pattern )
            {
                case Pattern.Direct:

                    //------- Direct List Data Access ------------------------------
                    // Adds a new SPListItem directly to the list.
                    SPList list = web.Lists[Lists.Announcements];
                    SPListItem item = list.Items.Add();
                    item[Fields.Title] = "Direct List Data Access";
                    item[Fields.Body] = "Item added using SPGSharePointDataAccessQuickStart Direct List Data Access.";
                    web.AllowUnsafeUpdates = true;
                    item.Update();
                    web.AllowUnsafeUpdates = false;
                    id = item.ID;
                    MessageLabel.Text = String.Format("Item added with the ID: {0} using the Direct pattern", item[Fields.Id].ToString());
                    //--------------------------------------------------------------

                    break;

                case Pattern.ListItemRepository:

                    //------- ListItemRepostitory Data Access ----------------------   
                    // Adds a new SPListItem using the ListItemRepository.
                    ListItemRepository listItemRepository = new ListItemRepository();
                    Dictionary<Guid, object> fields = new Dictionary<Guid, object>();
                    fields.Add(Fields.Title, "ListItemRepostitory Data Access");
                    fields.Add(Fields.Body, "Item added using SPGSharePointDataAccessQuickStart ListItemRepostitory Data Access.");
                    SPListItem item2 = listItemRepository.Add(web, Lists.Announcements, fields);
                    id = item2.ID;
                    MessageLabel.Text = String.Format("Item added with the ID: {0} using the ListItemRepository pattern", item2[Fields.Id].ToString());
                    //--------------------------------------------------------------

                    break;

                case Pattern.AnnouncementRepository:

                    //------- AnnoucementRepostitory Data Access -------------------   
                    // Adds a new Announcement using the AnnoucementRepostitory.
                    ListItemRepository listItemRepository2 = new ListItemRepository();
                    AnnouncementRepository annoucementRepository = new AnnouncementRepository(listItemRepository2);
                    Announcement annoucement = new Announcement();
                    annoucement.Title = "AnnoucementRepostitory Data Access";
                    annoucement.Body = "Item added using SPGSharePointDataAccessQuickStart AnnouncementRepository Data Access.";
                    id = annoucementRepository.Add(annoucement, web);
                    MessageLabel.Text = String.Format("Item added with the ID: {0} using the AnnouncementRepository pattern", id);
                    //--------------------------------------------------------------

                    break;
            }
        }

        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        private void PerformGet(SPWeb web)
        {
            switch ( pattern )
            {
                case Pattern.Direct:

                    //------- Direct List Data Access ------------------------------
                    // Gets a SPListItem directly from the list with a specified ID.
                    SPList list = web.Lists[Lists.Announcements];
                    SPQuery query = new SPQuery();
                    query.Query = String.Format("<Where><Eq><FieldRef Name='ID'/><Value Type='Integer'>{0}</Value></Eq></Where>", id);
                    SPListItemCollection items = list.GetItems(query);
                    if ( items.Count == 1 )
                    {
                        SPListItem item = items[0];
                        GetLabel.Text = String.Format("[{0}] {1} {2}", item.ID, item.Title, item[Fields.Body].ToString());
                        UpdateButton.Visible = true;
                        DeleteButton.Visible = true;
                    }
                    //--------------------------------------------------------------

                    break;

                case Pattern.ListItemRepository:

                    //------- ListItemRepostitory Data Access ----------------------   
                    // Gets a SPListItem using the ListItemRepository with a specified ID.
                    ListItemRepository listItemRepository = new ListItemRepository();
                    SPQuery query2 = new SPQuery();
                    query2.Query = String.Format("<Where><Eq><FieldRef Name='ID'/><Value Type='Integer'>{0}</Value></Eq></Where>", id);
                    SPListItem item2 = listItemRepository.Get(web, Lists.Announcements, query2);
                    if ( item2 != null )
                    {
                        GetLabel.Text = String.Format("[{0}] {1} {2}", item2.ID, item2.Title, item2[Fields.Body].ToString());
                        UpdateButton.Visible = true;
                        DeleteButton.Visible = true;
                    }
                    //--------------------------------------------------------------

                    break;

                case Pattern.AnnouncementRepository:

                    //------- AnnoucementRepostitory Data Access -------------------   
                    // Gets an Announcement using the AnnoucementRepostitory.
                    ListItemRepository listItemRepository2 = new ListItemRepository();
                    AnnouncementRepository annoucementRepository = new AnnouncementRepository(listItemRepository2);
                    Announcement annoucement = annoucementRepository.Get(id, web);
                    if ( annoucement != null )
                    {
                        GetLabel.Text = String.Format("[{0}] {1} {2}", annoucement.Id, annoucement.Title, annoucement.Body);
                        UpdateButton.Visible = true;
                        DeleteButton.Visible = true;
                    }
                    //--------------------------------------------------------------

                    break;
            }
        }

        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        private void PerformUpdate(SPWeb web)
        {
            switch ( pattern )
            {
                case Pattern.Direct:

                    //------- Direct List Data Access ------------------------------      
                    // Updates the description of a SPListItem directly in a list with the specified ID.
                    SPList list = web.Lists[Lists.Announcements];
                    SPQuery query = new SPQuery();
                    query.Query = String.Format("<Where><Eq><FieldRef Name='ID'/><Value Type='Integer'>{0}</Value></Eq></Where>", id);
                    SPListItemCollection items = list.GetItems(query);
                    if ( items.Count == 1 )
                    {
                        SPListItem item = items[0];
                        item["Body"] = String.Format("Item updated at {0} using SPGSharePointDataAccessQuickStart Direct List Data Access.", DateTime.Now.ToString());
                        web.AllowUnsafeUpdates = true;
                        item.Update();
                        web.AllowUnsafeUpdates = false;
                        MessageLabel.Text = String.Format("Item with the ID: {0} was updated using the Direct pattern", item[Fields.Id].ToString());
                    }
                    //--------------------------------------------------------------

                    break;

                case Pattern.ListItemRepository:

                    //------- ListItemRepostitory Data Access ----------------------   
                    // Updates the description of a SPListItem using the ListItemRepository with a specified ID.
                    ListItemRepository listItemRepository = new ListItemRepository();
                    Dictionary<Guid, object> fields = new Dictionary<Guid, object>();
                    fields.Add(Fields.Body, String.Format("Item updated at {0} using SPGSharePointDataAccessQuickStart ListItemRepostitory Data Access.", DateTime.Now.ToString()));
                    listItemRepository.Update(web, Lists.Announcements, id, fields);
                    MessageLabel.Text = String.Format("Item with the ID: {0} was updated using the ListItemRepository pattern", id.ToString());
                    //--------------------------------------------------------------

                    break;

                case Pattern.AnnouncementRepository:

                    //------- AnnoucementRepostitory Data Access -------------------   
                    // Updates the description of an Announcement using the AnnoucementRepostitory.
                    ListItemRepository listItemRepository2 = new ListItemRepository();
                    AnnouncementRepository annoucementRepository = new AnnouncementRepository(listItemRepository2);
                    Announcement annoucement = annoucementRepository.Get(id, web);
                    if ( annoucement != null )
                    {
                        annoucement.Body = String.Format("Item updated at {0} using SPGSharePointDataAccessQuickStart AnnouncementRepository Data Access.", DateTime.Now.ToString());
                        annoucementRepository.Update(annoucement, web);
                        MessageLabel.Text = String.Format("Item with the ID: {0} was updated using the AnnouncementRepository pattern", annoucement.Id);
                    }
                    //--------------------------------------------------------------

                    break;
            }
        }

        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        private void PerformDelete(SPWeb web)
        {
            switch ( pattern )
            {
                case Pattern.Direct:

                    //------- Direct List Data Access ------------------------------      
                    // Deletes the SPListItem directly in a list with the specified ID.
                    SPList list = web.Lists[Lists.Announcements];
                    SPQuery query = new SPQuery();
                    query.Query = String.Format("<Where><Eq><FieldRef Name='ID'/><Value Type='Integer'>{0}</Value></Eq></Where>", id);
                    SPListItemCollection items = list.GetItems(query);
                    if ( items.Count == 1 )
                    {
                        SPListItem item = items[0];
                        web.AllowUnsafeUpdates = true;
                        item.Delete();
                        web.AllowUnsafeUpdates = false;
                        MessageLabel.Text = String.Format("Item with the ID: {0} was deleted using the Direct pattern", id);
                    }
                    //--------------------------------------------------------------

                    break;

                case Pattern.ListItemRepository:

                    //------- ListItemRepostitory Data Access ----------------------   
                    // Deletes the SPListItem using the ListItemRepository with a specified ID.
                    ListItemRepository listItemRepository = new ListItemRepository();
                    listItemRepository.Delete(web, Lists.Announcements, id);
                    MessageLabel.Text = String.Format("Item with the ID: {0} was deleted using the ListItemRepository pattern", id);
                    //--------------------------------------------------------------

                    break;

                case Pattern.AnnouncementRepository:

                    //------- AnnoucementRepostitory Data Access -------------------   
                    // Deletes the Announcement using the AnnoucementRepostitory with a specified ID.
                    ListItemRepository listItemRepository2 = new ListItemRepository();
                    AnnouncementRepository annoucementRepository = new AnnouncementRepository(listItemRepository2);
                    annoucementRepository.Delete(id, web);
                    MessageLabel.Text = String.Format("Item with the ID: {0} was deleted using the AnnouncementRepository pattern", id);
                    //--------------------------------------------------------------

                    break;
            }
        }

        #endregion

        private void ResetView(SPWeb web)
        {
            GetLabel.Text = String.Empty;
            UpdateButton.Visible = false;
            DeleteButton.Visible = false;
            if ( IDsList.SelectedIndex != -1 )
            {
                id = Convert.ToInt32(IDsList.SelectedValue);
                PerformGet(web);
            }
            else
            {
                PopulateIDsList(web);
                if ( IDsList.SelectedIndex != -1 )
                {
                    id = Convert.ToInt32(IDsList.SelectedValue);
                    PerformGet(web);
                }
            }
        }

        private static Pattern ParsePattern(string selectedPattern)
        {
            return (Pattern)Enum.Parse(typeof(Pattern), selectedPattern);
        }

        private void PopulateIDsList(SPWeb web)
        {
            IDsList.DataSource = web.Lists[Lists.Announcements].Items;
            IDsList.DataTextField = "ID";
            IDsList.DataValueField = "ID";
            IDsList.DataBind();
        }

        private enum Pattern
        {
            Direct,
            ListItemRepository,
            AnnouncementRepository
        }
    }
}
